const emojy = document.querySelector("#emojy");
let markEmojy = true;

//调整表情框
function dropup() {
    if (markEmojy === false) {
        markEmojy = true;
        emojy.style.height = "0";
        emojy.style.width = "0";
        emojy.style.padding = "0";
        return;
    }
    markEmojy = false;
    emojy.style.padding = "20px";
    emojy.style.height = "250px";
    emojy.style.width = "320px";
}

//调整表情框
function drophide() {
    markEmojy = true;
    emojy.style.height = "0";
    emojy.style.width = "0";
    emojy.style.padding = "0";
}

//点击表情
function addEmojy(e) {
    drophide();
    const input = document.querySelector(".input");
    const startPos = input.selectionStart;
    const endPos = input.selectionEnd;
    // 插入文本到光标位置
    input.value = input.value.substring(0, startPos) + e.dataset["value"] + input.value.substring(startPos, input.value.length);
}

//表情json数据
let emojyData = {
    "[中毒]": "#icon--astonished",
    "[天使]": "#icon--angel",
    "[中毒-1]": "#icon--astonished-",
    "[酷]": "#icon--cool",
    "[迷茫]": "#icon--confused",
    "[生气]": "#icon--angry",
    "[酷-1]": "#icon--cool-",
    "[头晕]": "#icon--dizzy",
    "[哭]": "#icon--cry",
    "[哭-1]": "#icon--cry-",
    "[面无表情]": "#icon--expressionless",
    "[魔鬼]": "#icon--devil",
    "[懵逼]": "#icon--flushed",
    "[开心-1]": "#icon--happy-",
    "[开心-2]": "#icon--happy-1",
    "[开心]": "#icon--happy",
    "[受伤]": "#icon--injury",
    "[笑哭]": "#icon--joy",
    "[热恋]": "#icon--in-love",
    "[亲吻]": "#icon--kiss",
    "[亲吻-2]": "#icon--kiss-",
    "[亲吻-1]": "#icon--kiss-1",
    "[口罩]": "#icon--mask",
    "[面无表情-1]": "#icon--neutral",
    "[静音]": "#icon--mute",
    "[难过]": "#icon--sad",
    "[难过-1]": "#icon--sad-",
    "[害怕]": "#icon--scared",
    "[闭嘴]": "#icon--secret",
    "[害怕-1]": "#icon--scared-",
    "[震惊-1]": "#icon--shocked",
    "[生病]": "#icon--sick",
    "[笑]": "#icon--smile",
    "[笑-1]": "#icon--smile-",
    "[睡觉]": "#icon--sleeping",
    "[微笑-1]": "#icon--smiling-",
    "[眼红]": "#icon--smiling",
    "[流汗]": "#icon--sweat",
    "[震惊]": "#icon--surprised",
    "[奸笑]": "#icon--smirking",
    "[思考]": "#icon--thinking",
    "[疲惫]": "#icon--tired",
    "[吐舌]": "#icon--tongue",
    "[吐舌-1]": "#icon--tongue-",
    "[吐舌-2]": "#icon--tongue-1",
    "[斜眼]": "#icon--unamused",
    "[眨眼]": "#icon--wink",
    "[呕吐]": "#icon--vomiting",
    "[僵尸]": "#icon--zombie",
    "[呕吐-1]": "#icon--vomiting-"
};

//将表情代码替换成svg
function refreshEmojy() {
    let pattern = /\[(.*?)\]/g
    const chatView = document.querySelector("#chat-view");
    let innerHTML = chatView.innerHTML;
    let keys = innerHTML.match(pattern);
    if (keys === null) {
        return;
    }
    for (let i = 0; i < keys.length; i++) {
        let emojyDatum = emojyData[keys[i]];
        if (emojyDatum !== undefined) {
            innerHTML = innerHTML.replace(keys[i], '<svg class="emojy-input" aria-hidden="true">' + '<use xlink:href="' + emojyData[keys[i]] + '"></use>' + '</svg>')
        }
    }
    chatView.innerHTML = innerHTML;
}

// setInterval(refreshEmojy, 500)

const navbarMorebar = document.querySelector("#navbar-morebar");
let markMore = true;

//调整更多栏大小
function more() {
    if (markMore === false) {
        markMore = true;
        navbarMorebar.style.height = "0";
        navbarMorebar.style.padding = "0";
        return;
    }
    markMore = false;
    navbarMorebar.style.height = "200px";
    navbarMorebar.style.padding = "10px";
}

//点击聊天目标
function display(e) {
    document.querySelector("#page").value = 0;
    let friendId = e.childNodes[3].childNodes[1].value;
    let userId = document.querySelector("#userId").value
    let friendPetname = e.childNodes[3].childNodes[5].innerText;
    let page = document.querySelector("#page").value;
    document.querySelector("#messageType").value = "nomal"
    new Promise(() => {
        $.ajax({
            url: `/chat/getMessageHistory?userId=${userId}&friendId=${friendId}&page=${page}`,
            success(data) {
                console.log(data)
                displayChatView(data, userId, friendPetname, friendId);
            },
            error() {

            }
        })
    })
}

//显示聊天窗口
function displayChatView(messageData, userId, friendPetname, friendId) {
    /*
    <div class="col-md-12 chat-message my">
        <div class="card">
            <div class="card-body">
                Lorem
            </div>
        </div>
        <img src="image/user.png" class="middle-user-head" alt="头像">
    </div>

    dateFormat: "2024/03/27-18:09:34"
    from: 10002
    message: "hi"
    messageId: 5
    messageTime: 1711534174622
    messageType: "regular"
    receive: false
    to: 10000
     */
    document.querySelector("#chat-name").innerText = friendPetname;
    document.querySelector("#friendId").value = friendId;
    let userHead = document.querySelector("#userHead").src;
    const chatView = document.querySelector("#chat-view");
    chatView.innerHTML = "";
    //将获取到的长度放到隐藏域
    const messageSize = document.querySelector("#messageSize");
    messageSize.value = messageData.length;
    for (let i = 0; i < messageData.length; i++) {

        let timeSplit = messageData[i].dateFormat.split("-");

        chatView.innerHTML += `<div class="message-time">${timeSplit[0] + " " + timeSplit[1]}</div>`;

        if (messageData[i].from === parseInt(userId)) {
            chatView.innerHTML += `<div class='col-md-12 chat-message my'><div class='card'><div class='card-body'>${messageData[i].message}</div></div><img src='${userHead}' class='middle-user-head' alt='头像'></div>`;
        } else {
            let friendHead = document.getElementById(messageData[i].from + "-head").src;
            chatView.innerHTML += `<div class='col-md-12 chat-message'><img src='${friendHead}' class='middle-user-head' alt='头像'><div class='card'><div class='card-body'>${messageData[i].message}</div></div></div>`;
        }
    }

    // //将服务器同步过来的最新的一条消息显示在好友列表中
    // let newMessage = messageData[messageData.length - 1];
    // //好友列表显示
    // let friendMessageBar = document.getElementById(`${friendId}`);
    // friendMessageBar.innerText = newMessage.message.replace(/\\n/g, " ");
    //
    // //显示时间
    // let time = friendMessageBar.previousSibling.previousSibling.previousSibling.previousSibling;
    // time.innerText = `${newMessage.dateFormat.split("-")[1]}`;

    refreshEmojy();
    //显示对话页面
    document.querySelector("#chat-bar").style.display = "inline-block";
    //显示最新消息
    chatView.scrollTop = chatView.scrollHeight;
}

const input = document.querySelector("#input");
// 定义一个对象来跟踪当前按下的键
let pressedKeys = {};

function startKeyboardListener() {
    //键盘按下事件
    document.addEventListener("keydown", keydownFun);
    //键盘释放事件
    document.addEventListener("keyup", keyupFun);
}
function keydownFun(event) {
    // 将按下的键添加到 pressedKeys 对象中
    pressedKeys[event.key] = true;

    //同时按下 Control 和 Enter 是换行
    if (pressedKeys["Control"] && pressedKeys["Enter"]) {
        const input = document.querySelector(".input");
        const startPos = input.selectionStart;
        // 插入换行到光标位置
        input.value = input.value.substring(0, startPos) + "\n" + input.value.substring(startPos, input.value.length);
        // 设置新的光标位置
        const newCursorPosition = startPos + 1; // 新的光标位置在换行符之后
        input.setSelectionRange(newCursorPosition, newCursorPosition);
        return
    }
    //只按下 Enter 是发送消息
    if (pressedKeys["Enter"] && input.value.trim() !== "") {
        //阻止Enter键默认行为
        event.preventDefault();
        let replace = input.value.replace(/\n/g, "\\n");
        console.log(replace)
        let messageType = document.querySelector("#messageType").value;
        if (messageType === "nomal") {
            sendMessage(replace, messageType);
        }
        if (messageType === "group") {
            sendGroupMessage(replace, messageType);
        }
        if (messageType === "AIChat") {
            sendToAI(replace, messageType)
        }
        input.value = "";
        return;
    }

}

function keyupFun(event) {
    // 将释放的键从 pressedKeys 对象中移除
    delete pressedKeys[event.key]
}

function removeKeyboardListener() {
    document.removeEventListener("keydown", keydownFun);
    document.removeEventListener("keyup", keyupFun);
}

//文本域获得焦点事件
input.addEventListener("focus", startKeyboardListener);
//文本域失去焦点事件
input.addEventListener("blur", removeKeyboardListener)

function sendMessage(message, messageType) {
    /*
    {"messageId":4,"from":10000,"to":10002,"message":"hello","messageTime":1711534174608,"dateFormat":"2024/03/27-18:09:34","messageType":"regular","receive":false}
     */
    let friendId = document.querySelector("#friendId").value;
    const userId = document.querySelector("#userId").value;
    let userHead = document.querySelector("#userHead").src;
    let sendContent = `{"from":${userId},"to":${friendId},"message":"${message.replace(/"/g, "\\\"")}","messageType":"${messageType}"}`;
    ws.send(sendContent);

    const chatView = document.querySelector("#chat-view");

    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() > 9 ? date.getMonth() : "0" + date.getMonth();
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    let hours = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    let minutes = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    let seconds = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();

    //聊天页面显示时间
    chatView.innerHTML += `<div class="message-time">${year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds}</div>`;
    //页面显示
    let replace = message.replace(/\\n/g, "<br/>"); //将换行符替换成<br/>
    chatView.innerHTML += `<div class='col-md-12 chat-message my'><div class='card'><div class='card-body'>${replace}</div></div><img src='${userHead}' class='middle-user-head' alt='头像'></div>`;

    //好友列表显示
    let friendMessageBar = document.getElementById(`${friendId}`);
    friendMessageBar.innerText = message.replace(/\\n/g, " ");

    //显示时间
    let time = friendMessageBar.previousSibling.previousSibling.previousSibling.previousSibling;

    time.innerText = `${hours + ":" + minutes + ":" + seconds}`;

    refreshEmojy()
    chatView.scrollTop = chatView.scrollHeight;
}

function sendGroupMessage(message, messageType) {
    let groupId = document.querySelector("#friendId").value;
    const userId = document.querySelector("#userId").value;
    let userHead = document.querySelector("#userHead").src;
    let sendContent = `{"senderId":${userId},"groupId":${groupId},"content":"${message.replace(/"/g, "\\\"")}","messageType":"${messageType}"}`;
    ws.send(sendContent);

    const chatView = document.querySelector("#chat-view");

    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() > 9 ? date.getMonth() : "0" + date.getMonth();
    let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    let hours = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    let minutes = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    let seconds = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();

    //聊天页面显示时间
    chatView.innerHTML += `<div class="message-time">${year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds}</div>`;
    //页面显示
    let replace = message.replace(/\\n/g, "<br/>");
    chatView.innerHTML += `<div class='col-md-12 chat-message my'><div class='card'><div class='card-body'>${replace}</div></div><img src='${userHead}' class='middle-user-head' alt='头像'></div>`;

    refreshEmojy()
    //滚动到最底部
    chatView.scrollTop = chatView.scrollHeight;
}

//重新加载好友列表
function reloadFriendList() {

    //隐藏清除缓存按钮和提示
    document.querySelector("#clearLocalStorage").style.display = "none";
    document.querySelector("#aiTip").style.display = "none"

    //取消readonly
    document.querySelector("#input").readOnly = false;

    //将groupId删除
    document.querySelector("#groupId").innerText = "";

    //显示更多按钮
    document.querySelector("#chat-bar-head-more").style.display = "inline-block";

    //将搜索框的placeholder设置为搜索好友
    const search = document.querySelector(".search");
    search.value = "";
    search.placeholder = "搜索好友"
    //重新显示表情按钮
    document.querySelector(".icon-weixiao").style.display = "inline-block";
    let chatView = document.querySelector("#chat-view");
    chatView.innerHTML = "";
    document.querySelector("#chat-bar").style.display = "none";
    document.querySelector("#messageType").value = "nomal"
    new Promise(() => {
        $.ajax({
            url: "/chat/getFriendList",
            success(data) {
                updateFriendList(data);
            },
            error() {

            }
        })
    })
}

//将取得的好友列表数据显示出来
function updateFriendList(data) {
    /*
    <li class="list-group-item middle-list-item" onclick="display(this)" th:each="friend:${friendList}">
        <img src="image/user.png" class="middle-user-head" alt="头像">
        <div class="middle-message" th:with="msg=${newMessage.get(friend.userid.toString())}">
            <input type="hidden" name="friendid" th:value="${friend.userid}">
            <input type="hidden" name="userid" th:value="${session.user.userid}">
            <span class="middle-petname" th:text="${friend.petName}">用户昵称</span>
            <span class="middle-chat-time" id="middle-chat-time" th:text="${msg == null ? '' : msg.getDateFormat().split('-')[1]}"></span> <br>
            <span class="middle-chat-content" th:id="${friend.userid}" th:text="${msg == null ? '' : msg.message}"></span>
        </div>
    </li>
     */
    const userId = document.querySelector("#userId");
    let friendList = data.friendList;
    let newMessages = data.newMessage;
    let list = document.querySelector("#list");
    list.innerHTML = "";
    console.log(data)
    for (let i = 0; i < friendList.length; i++) {
        let friendId = friendList[i].userid;
        let petName = friendList[i].petName;
        let headImage = friendList[i].headImage;
        let newMessage = newMessages[friendId];
        let message = "";
        let dateFormat = "";
        if (newMessage !== null) {
            message = newMessage.message === undefined ? "" : newMessage.message;
            dateFormat = (newMessage.dateFormat === undefined ? "" : newMessage.dateFormat).split("-")[1];
        }
        list.innerHTML += `<li class="list-group-item middle-list-item" onclick="display(this)"> <img src="${headImage === null ? 'image/user.png' : headImage}" id="${friendId + '-head'}" class="middle-user-head" alt="头像"/> <div class="middle-message"> <input type="hidden" name="friendid" value="${friendId}"> <input type="hidden" name="userid" value="${userId}"> <span class="middle-petname">${petName}</span> <span class="middle-chat-time" id="middle-chat-time">${dateFormat}</span> <br> <span class="middle-chat-content" id="${friendId}">${message}</span> </div> </li>`;
    }

    let flexible = document.querySelector("#flexible");
    flexible.style.transform = "rotate(0deg)";
    flexible.style.display = "inline-block";
    document.querySelector("#middle-bar").style.width = "280px";
}

let headBarDisplay = false;

function headbar() {
    const headBar = document.querySelector("#head-bar");
    if (!headBarDisplay) {
        headBarDisplay = true;
        headBar.style.width = "250px";
        return
    }
    headBarDisplay = false;
    headBar.style.width = "0";
}

const selectHeadImage = document.querySelector("#selectHeadImage");
const userHeadIcon = document.querySelectorAll(".user-head-icon");

function selectImage() {
    selectHeadImage.click();
}

selectHeadImage.addEventListener("change", function (event) {
    //检查是否读取文件
    if (selectHeadImage.files && selectHeadImage.files[0]) {
        // 创建文件读取器
        const reader = new FileReader();

        const maxSize = 1024 * 1024;

        if (event.target.files[0].size > maxSize) {
            alert("文件大小超出上限1MB");
            return;
        }

        reader.onload = function (e) {
            userHeadIcon[0].src = e.target.result;
            userHeadIcon[1].src = e.target.result;
            //将头像数据传回服务器
            sendHeadImage(selectHeadImage.files[0]);
        }

        reader.readAsDataURL(selectHeadImage.files[0]);
    }
})

function sendHeadImage(file) {
    const formData = new FormData();
    formData.append("headImage", file);
    new Promise(() => {
        $.ajax({
            url: "/chat/upload/headImage",
            method: "POST",
            data: formData,
            contentType: false, //浏览器自动设置Content-Type
            processData: false, //不将该数据设置为字符串
            success() {
                alert("头像修改成功!");
            },
            error() {

            }
        });
    });
}

//加载群组列表
function reloadGroupList() {
    //隐藏清除缓存按钮和提示
    document.querySelector("#clearLocalStorage").style.display = "none";
    document.querySelector("#aiTip").style.display = "none"
    //取消readonly
    document.querySelector("#input").readOnly = false;

    document.querySelector("#chat-bar-head-more").style.display = "inline-block";
    const search = document.querySelector(".search");
    search.value = "";
    search.placeholder = "搜索群组"
    document.querySelector(".icon-weixiao").style.display = "inline-block";
    document.querySelector("#messageType").value = "group"
    new Promise(() => {
        $.ajax({
            url: "/chat/groupList",
            success(resultData) {
                updateGroupList(resultData);
            },
        });
    });
}

function updateGroupList(groupList) {
    let userId = document.querySelector("#userId").value;
    let list = document.querySelector("#list");
    list.innerHTML = "";
    for (let i = 0; i < groupList.length; i++) {
        let groupHead = groupList[i].groupHead;
        let groupId = groupList[i].groupId;
        let groupName = groupList[i].groupName;
        list.innerHTML += `<li class="list-group-item middle-list-item" onclick="displayGroupChat(this)"> <img src="${groupHead === null ? 'image/group.png' : groupHead}" class="middle-user-head" alt="头像"/> <div class="middle-message"> <input type="hidden" name="groupId" value="${groupId}"> <input type="hidden" name="userid" value="${userId}"> <span class="middle-petname">${groupName}</span> </div> </li>`;
    }
    document.querySelector("#chat-view").innerHTML = "";
    document.querySelector("#chat-bar").style.display = "none";
    let flexible = document.querySelector("#flexible");
    flexible.style.transform = "rotate(0deg)";
    flexible.style.display = "inline-block";
    document.querySelector("#middle-bar").style.width = "280px";
}


function displayGroupChat(elemet) {
    document.querySelector("#page").value = 0;
    let groupId = elemet.childNodes[3].childNodes[1].value;
    let groupName = elemet.childNodes[3].childNodes[5].innerText;
    let page = document.querySelector("#page").value;
    document.querySelector("#messageType").value = "group"
    new Promise(() => {
        $.ajax({
            url: `/chat/groupMessageHistory?groupId=${groupId}&page=${page}`,
            success(resultData) {
                displayGroupChatView(resultData, groupId, groupName);
            },
            error() {

            }
        });
    });
}

function displayGroupChatView(groupData, groupId, groupName) {
    //将获取到的消息长度放到隐藏域
    const messageSize = document.querySelector("#messageSize");
    messageSize.value = groupData.messageData.length;

    document.querySelector("#friendId").value = groupId;
    document.querySelector("#chat-name").innerText = groupName;
    let userId = document.querySelector("#userId").value;
    let userHead = document.querySelector("#userHead").src;

    const chatView = document.querySelector("#chat-view");
    chatView.innerHTML = "";

    for (let i = 0; i < groupData.messageData.length; i++) {

        let timeSplit = groupData.messageData[i].dateFormat.split("-");
        let senderHead = groupData.messageData[i].senderHead;
        let senderPetName = groupData.messageData[i].senderPetName;

        chatView.innerHTML += `<div class="message-time">${timeSplit[0] + " " + timeSplit[1]}</div>`;

        if (groupData.messageData[i].senderId === parseInt(userId)) {
            chatView.innerHTML += `<div class='col-md-12 chat-message my'><div class='card'><div class='card-body'>${groupData.messageData[i].content}</div></div><img src='${userHead}' class='middle-user-head' alt='头像'></div>`;
        } else {
            chatView.innerHTML += `<div class='col-md-12 chat-message'><div id="senderPetName">${senderPetName}</div><img src='${senderHead}' class='middle-user-head' alt='头像'><div class='card sender'><div class='card-body'>${groupData.messageData[i].content}</div></div></div>`;
        }
    }

    document.querySelector("#groupId").innerText = "群组ID:" + groupId

    document.querySelector("#chat-bar").style.display = "inline-block";
    refreshEmojy();
    chatView.scrollTop = chatView.scrollHeight;

    //改变文字和绑定的函数
    document.querySelector("#role").value = groupData.role;
    let deleteGroupeElement = document.querySelector("#deleteGroup");
    if (groupData.role === 0) {
        deleteGroupeElement.innerText = "解散该群聊";
        deleteGroupeElement.onclick = deleteGroup;
    } else {
        deleteGroupeElement.innerText = "退出该群聊";
        deleteGroupeElement.onclick = quitGroup;
    }
}

function hideMiddleBar() {
    let middleBar = document.querySelector("#middle-bar");
    let flexible = document.querySelector("#flexible");
    let computedStyle = window.getComputedStyle(middleBar);

    if (computedStyle.width === "280px") {
        flexible.style.transform = "rotate(180deg)";
        middleBar.style.width = "0";
    }
    if (computedStyle.width === "1px") {
        flexible.style.transform = "rotate(0deg)";
        middleBar.style.width = "280px";
    }
}

function openAI() {
    //显示清除缓存按钮和提示
    document.querySelector("#clearLocalStorage").style.display = "block";
    document.querySelector("#aiTip").style.display = "inline-block"
    //将groupId删除
    document.querySelector("#groupId").innerText = "";

    document.querySelector("#chat-bar-head-more").style.display = "none";
    document.querySelector(".icon-weixiao").style.display = "none";

    const middleBar = document.querySelector("#middle-bar");
    middleBar.style.width = "0";
    let flexible = document.querySelector("#flexible");
    flexible.style.display = "none";

    const chatName = document.querySelector("#chat-name");
    chatName.innerText = "AI君";

    const chatView = document.querySelector("#chat-view");
    chatView.innerHTML = "";

    chatView.innerHTML += `<div class='col-md-12 chat-message'><span class="iconfont icon-rengongzhineng opai-head"></span><div class='card response-card'><textarea class='card-body response' readonly>你好！有什么可以帮助你的吗？</textarea></div></div>`;
    document.querySelector("#chat-bar").style.display = "inline-block";

    document.querySelector("#messageType").value = "AIChat";

    const userHead = document.querySelector("#userHead").src;
    //从localStorage中加载和AI的聊天缓存数据
    for (let i = 0; i < localStorage.length; i++) {
        let item = localStorage.getItem(i.toString());
        let toJson = JSON.parse(item);
        let send = Object.keys(toJson)[0];
        let receive = toJson[send];
        // 创建新的发送消息元素
        const sendMessage = document.createElement('div');
        sendMessage.classList.add('col-md-12', 'chat-message', 'my');
        sendMessage.innerHTML = `<div class='card response-card'><textarea class='card-body response' readonly></textarea></div><img src='${userHead}' class='middle-user-head' alt='头像'>`;
        chatView.appendChild(sendMessage);

        let cardBodyList = document.querySelectorAll(".response");
        cardBodyList[cardBodyList.length - 1].value = send.replace(/\\n/g, "\n")

        cardBodyList = document.querySelectorAll(".response");
        autoResize(cardBodyList[cardBodyList.length - 1])

        // 创建新的聊天消息元素
        const chatMessage = document.createElement('div');
        chatMessage.classList.add('col-md-12', 'chat-message');
        chatMessage.innerHTML = `<span class="iconfont icon-rengongzhineng opai-head"></span><div class='card response-card'><div class='card-body response'"></div></div>`;

        chatView.appendChild(chatMessage)

        cardBodyList = document.querySelectorAll(".response");
        cardBodyList[cardBodyList.length - 1].value = receive

        {
            const strings = receive.split("\n");
            let flag = false;
            let type;

            const div = cardBodyList[cardBodyList.length - 1];
            let pre;
            for (let i = 0; i < strings.length; i++) {
                const row = strings[i].trim();
                if (row.includes("```") && row !== "```") {
                    type = strings[i].split("```")[1];
                    flag = true;

                    const p = document.createElement("p");
                    p.appendChild(document.createTextNode(type));
                    p.style.borderTopLeftRadius = "10px";
                    p.style.borderTopRightRadius = "10px";
                    p.style.margin = "0";
                    p.style.backgroundColor = "white";
                    p.style.color = "gray";
                    p.style.fontSize = "13px"
                    p.style.paddingLeft = "20px";
                    div.appendChild(p);

                    pre = document.createElement("pre");
                    pre.style.backgroundColor = "#EEE";
                    pre.style.borderBottomLeftRadius = "10px";
                    pre.style.borderBottomRightRadius = "10px";
                    pre.style.padding = "10px"
                    div.appendChild(pre)
                    continue;
                }
                if (row === "```") {
                    flag = false;
                    continue;
                }
                if (flag) {
                    const code = document.createElement("code");
                    code.classList.add(type);
                    code.innerHTML = hljs.highlightAuto(strings[i]).value + "\n";
                    pre.appendChild(code);
                } else {
                    if (strings[i].trim() !== "") {
                        const p = document.createElement("p");
                        p.innerHTML += strings[i];
                        div.appendChild(p);
                    }
                }
            }
            div.classList.add("card-body", "response");
        }

        //滚动到最底部
        chatView.scrollTop = chatView.scrollHeight;
    }
}

function sendToAI(message, messageType) {
    document.querySelector("#input").readOnly = true;

    const chatView = document.querySelector("#chat-view");

    const userHead = document.querySelector("#userHead").src;

    // 创建新的发送消息元素
    const sendMessage = document.createElement('div');
    sendMessage.classList.add('col-md-12', 'chat-message', 'my');
    sendMessage.innerHTML = `<div class='card response-card'><textarea class='card-body response' readonly></textarea></div><img src='${userHead}' class='middle-user-head' alt='头像'>`;
    chatView.appendChild(sendMessage);
    //.replace(/\n/g, "<br/>")
    let cardBodyList = document.querySelectorAll(".response");
    cardBodyList[cardBodyList.length - 1].value = message.replace(/\\n/g, "\n");
    autoResize(cardBodyList[cardBodyList.length - 1])

    cardBodyList = document.querySelectorAll(".response");
    autoResize(cardBodyList[cardBodyList.length - 1])

    // 创建新的聊天消息元素
    const chatMessage = document.createElement('div');
    chatMessage.classList.add('col-md-12', 'chat-message');
    chatMessage.innerHTML = `<span class="iconfont icon-rengongzhineng opai-head"></span><div class='card response-card'><div class='card-body response'"></div></div>`;

    chatView.appendChild(chatMessage)

    //滚动到最底部
    chatView.scrollTop = chatView.scrollHeight;

    cardBodyList = document.querySelectorAll(".response");

    // 创建 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest();
    // 设置请求的 URL
    xhr.open('POST', `/chat/AIChat`, true);
    // 设置响应类型为 text/event-stream
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // 监听 readyStateChange 事件
    xhr.onreadystatechange = () => {
        // 如果 readyState 是 3，表示正在接收数据
        if (xhr.readyState === 3) {
            // 将数据添加到响应框中
            // cardBodyList[cardBodyList.length - 1].value = xhr.responseText;

            {
                const strings = xhr.responseText.split("\n");
                let flag = false;
                let type;

                const div = cardBodyList[cardBodyList.length - 1];
                div.innerHTML = "";
                let pre;
                for (let i = 0; i < strings.length; i++) {
                    const row = strings[i].trim();
                    if (row.includes("```") && row !== "```") {
                        type = strings[i].split("```")[1];
                        flag = true;

                        const p = document.createElement("p");
                        p.appendChild(document.createTextNode(type));
                        p.style.borderTopLeftRadius = "10px";
                        p.style.borderTopRightRadius = "10px";
                        p.style.margin = "0";
                        p.style.backgroundColor = "white";
                        p.style.color = "gray";
                        p.style.fontSize = "13px"
                        p.style.paddingLeft = "20px";
                        div.appendChild(p);

                        pre = document.createElement("pre");
                        pre.style.backgroundColor = "#EEE";
                        pre.style.borderBottomLeftRadius = "10px";
                        pre.style.borderBottomRightRadius = "10px";
                        pre.style.padding = "10px"
                        div.appendChild(pre)
                        continue;
                    }
                    if (row === "```") {
                        flag = false;
                        continue;
                    }
                    if (flag) {
                        const code = document.createElement("code");
                        code.classList.add(type);
                        code.innerHTML = hljs.highlightAuto(strings[i]).value + "\n";
                        pre.appendChild(code);
                    } else {
                        if (strings[i].trim() !== "") {
                            const p = document.createElement("p");
                            p.innerHTML += strings[i];
                            div.appendChild(p);
                        }
                    }
                }
                div.classList.add("card-body", "response");
            }

            autoResize(cardBodyList[cardBodyList.length - 1])
        }
        // 如果 readyState 是 4，表示完成请求
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 避免接受过程中缺少字符

                //创建记录消息的对象
                let order = {};
                order[message] = xhr.responseText
                localStorage.setItem(localStorage.length.toString(), JSON.stringify(order));
                document.querySelector("#input").readOnly = false;

                //代码块 处理最后的显示
                {
                    const strings = xhr.responseText.split("\n");
                    let flag = false;
                    let type;

                    const div = cardBodyList[cardBodyList.length - 1];
                    div.innerHTML = "";
                    let pre;
                    for (let i = 0; i < strings.length; i++) {
                        const row = strings[i].trim();
                        if (row.includes("```") && row !== "```") {
                            type = strings[i].split("```")[1];
                            flag = true;

                            const p = document.createElement("p");
                            p.appendChild(document.createTextNode(type));
                            p.style.borderTopLeftRadius = "10px";
                            p.style.borderTopRightRadius = "10px";
                            p.style.margin = "0";
                            p.style.backgroundColor = "white";
                            p.style.color = "gray";
                            p.style.fontSize = "13px"
                            p.style.paddingLeft = "20px";
                            div.appendChild(p);

                            pre = document.createElement("pre");
                            pre.style.backgroundColor = "#EEE";
                            pre.style.borderBottomLeftRadius = "10px";
                            pre.style.borderBottomRightRadius = "10px";
                            pre.style.padding = "10px"
                            div.appendChild(pre)
                            continue;
                        }
                        if (row === "```") {
                            flag = false;
                            continue;
                        }
                        if (flag) {
                            const code = document.createElement("code");
                            code.classList.add(type);
                            code.innerHTML = hljs.highlightAuto(strings[i]).value + "\n";
                            pre.appendChild(code);
                        } else {
                            if (strings[i].trim() !== "") {
                                const p = document.createElement("p");
                                p.innerHTML += strings[i];
                                div.appendChild(p);
                            }
                        }
                    }
                    div.classList.add("card-body", "response");
                }
            }
        }
    }

    // 发送请求
    xhr.send(`content=${encodeURIComponent(message.replace(/\n/g, "\\n"))}`);
}

//将文本域高度自动变高
function autoResize(textarea) {
    textarea.style.height = 'auto';
    textarea.style.height = (textarea.scrollHeight) + 10 + 'px';
    const chatView = document.querySelector("#chat-view");
    //滚动到最底部
    chatView.scrollTop = chatView.scrollHeight;
}

function searchList(elemet) {
    let listGroupItem = document.querySelectorAll(".list-group-item");
    for (let i = 0; i < listGroupItem.length; i++) {
        let node = listGroupItem[i].childNodes[3].childNodes[5];
        if (node.innerText.includes(elemet.value)) {
            listGroupItem[i].style.display = "inline-block";
        } else {
            listGroupItem[i].style.display = "none";
        }
        if (node.innerText === "") {
            listGroupItem[i].style.display = "inline-block";
        }
    }
}

function closeParent(elemet) {
    elemet.parentNode.style.display = "none";
}

function displayBanner(value) {

    //让更多栏缩回去
    markMore = true;
    navbarMorebar.style.height = "0";
    navbarMorebar.style.padding = "0";

    const search = document.querySelector("#search");
    const banner = document.querySelector("#banner");
    const userInfo = document.querySelector("#user-info");
    banner.style.display = "block";
    search.value = "";
    userInfo.style.display = "none";

    if (value === "addFriend") {
        search.placeholder = "输入用户名搜索用户"
        search.addEventListener("keydown", function (event) {
            if (event.key === "Enter") {
                searchUser(search.value);
            }
        })
    }
    if (value === "joinGroup") {
        search.placeholder = "输入群组ID搜索群组"
        search.addEventListener("keydown", function (event) {
            if (event.key === "Enter") {
                searchGroup(search.value);
            }
        })
    }
}

function searchUser(username) {
    new Promise(() => {
        $.ajax({
            url: `/chat/searchUser?username=${username}`,
            success(userData) {
                document.querySelector("#user-info").style.display = "none";
                if (userData !== "") {
                    showUserInfo(userData);
                }
            },
            error() {

            }
        });
    });
}

function showUserInfo(userData) {
    let userId = document.querySelector("#userId");
    //展示用户信息
    const userInfo = document.querySelector("#user-info");
    const userHead = document.querySelector("#search-user-head");
    const petName = document.querySelector("#search-user-petName");
    const username = document.querySelector("#search-user-username");
    const friendId = document.querySelector("#search-user-userId");
    const addFriendButton = document.querySelector("#addFriendButton");
    userHead.src = userData.headImage;
    petName.innerHTML = "昵&nbsp;&nbsp;&nbsp;&nbsp;称: " + userData.petName;
    username.innerText = "用户名: " + userData.username;
    friendId.innerText = "用户ID: " + userData.userid;

    userInfo.style.display = "block";

    if (userData.isFriend) {
        addFriendButton.innerText = "你已经是对方的好友了";
    } else {

        addFriendButton.innerText = "发送添加好友申请"

        addFriendButton.addEventListener("click", function () {

            let newNode = addFriendButton.cloneNode(true);
            addFriendButton.parentNode.replaceChild(newNode, addFriendButton);

            if (userId.value.toString() === userData.userid.toString()) {
                document.querySelector("#tip").click()
                document.querySelector("#exampleModalLabel").innerText = "系统提示"
                document.querySelector(".modal-body").innerHTML = "";
                document.querySelector(".modal-body").innerText = "你不可以对自己发出好友申请!"
                return;
            }

            let petName = document.querySelector("#petName").value;
            let sendContent = `{"from":${userId.value},"to":${userData.userid},"message":"${petName}","messageType":"friendRequest"}`;
            ws.send(sendContent);

            document.querySelector("#tip").click()
            document.querySelector("#exampleModalLabel").innerText = "系统提示"
            document.querySelector(".modal-body").innerHTML = "";
            document.querySelector(".modal-body").innerText = "好友申请已发出"
        });
    }
}

function searchGroup(groupId) {
    new Promise(() => {
        $.ajax({
            url: `/chat/searchGroup?groupId=${groupId}`,
            success(groupData) {
                document.querySelector("#user-info").style.display = "none";
                if (groupData !== "") {
                    showGroupInfo(groupData);
                }
            },
            error() {

            }
        });
    });
}

function showGroupInfo(groupData) {
    let userId = document.querySelector("#userId");
    //展示群组信息
    const groupInfo = document.querySelector("#user-info");
    const groupHead = document.querySelector("#search-user-head");
    const groupName = document.querySelector("#search-user-petName");
    const groupNumber = document.querySelector("#search-user-username");
    const groupId = document.querySelector("#search-user-userId");
    const joinGroupButton = document.querySelector("#addFriendButton");
    groupHead.src = groupData.groupHead;
    groupName.innerText = "群名称: " + groupData.groupName;
    groupNumber.innerText = "群组人数: " + groupData.groupNumber + " 人";
    groupId.innerText = "群组ID: " + groupData.groupId;

    groupInfo.style.display = "block";

    if (groupData.inGroup) {
        joinGroupButton.innerText = "你已经在该群中了"
    } else {
        joinGroupButton.innerText = "发送入群申请"
        joinGroupButton.addEventListener("click", function () {

            let newNode = joinGroupButton.cloneNode(true);
            joinGroupButton.parentNode.replaceChild(newNode, joinGroupButton);

            let petName = document.querySelector("#petName").value;
            let sendContent = `{"from":${userId.value},"to":${groupData.groupId},"message":"${petName}-${groupData.groupName}","messageType":"joinGroupRequest"}`;
            ws.send(sendContent);

            document.querySelector("#tip").click()
            document.querySelector("#exampleModalLabel").innerText = "系统提示"
            document.querySelector(".modal-body").innerHTML = "";
            document.querySelector(".modal-body").innerText = "入群申请已发出"
        });
    }
}

function getSystemMessage() {

    //让更多栏缩回去
    markMore = true;
    navbarMorebar.style.height = "0";
    navbarMorebar.style.padding = "0";

    let userId = document.querySelector("#userId");
    new Promise(() => {
        $.ajax({
            url: `/chat/getSystemMessage?userId=${userId.value}`,
            success(resultData) {
                showSystemMessage(resultData);
            },
            error() {

            }
        });
    });
}

function showSystemMessage(resultData) {
    const modalBody = document.querySelector(".modal-body");
    modalBody.innerHTML = "";
    modalBody.innerText = "";
    console.log(resultData)
    for (let i = 0; i < resultData.length; i++) {
        if (resultData[i].messageType === "friendRequest") {
            modalBody.innerHTML += `<div class="system-message"><div class="system-message-content">用户：<span class="user-prtName" style="vertical-align: bottom; display: inline-block; width: 200px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${resultData[i].message}</span> <br/>申请成为您的好友</div><button type="button" class="btn btn-success agree" data-friendid="${resultData[i].from}" data-messageid="${resultData[i].messageId}" onclick="agree(this)">同意</button><button type="button" class="btn btn-danger refuse" data-messageid="${resultData[i].messageId}" onclick="refuse(this)">拒绝</button></div>`;
        }
        if (resultData[i].messageType === "joinGroupRequest") {
            modalBody.innerHTML += `<div class="system-message"><div class="system-message-content">用户：<span class="user-prtName" style="vertical-align: bottom; display: inline-block; width: 200px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${resultData[i].message.split("-")[0]}</span> <br/>申请加入群组：<span style="vertical-align: bottom; display: inline-block; width: 200px;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${resultData[i].message.split("-")[1]}</span></div><button type="button" class="btn btn-success agree" data-groupid="${resultData[i].to}" data-userid="${resultData[i].from}" data-messageid="${resultData[i].messageId}" onclick="agreeGroup(this)">同意</button><button type="button" class="btn btn-danger refuse" data-messageid="${resultData[i].messageId}" onclick="refuseGroup(this)">拒绝</button></div>`;
        }
    }
    document.querySelector("#tip").click()
    document.querySelector("#exampleModalLabel").innerText = "系统消息"
}

function agree(elemet) {
    let messageId = elemet.dataset.messageid;
    let friendid = elemet.dataset.friendid;
    new Promise(() => {
        $.ajax({
            url: `/chat/addFriend?messageId=${messageId}&friendId=${friendid}`,
            success() {
                alert("已同意该好友申请");
                reloadFriendList();
            },
            error() {

            }
        });
    });
    elemet.parentNode.style.display = "none";
}

function refuse(elemet) {
    let messageId = elemet.dataset.messageid;

    new Promise(() => {
        $.ajax({
            url: `/chat/deleteMessageById?messageId=${messageId}`,
            success() {
                alert("已拒绝该好友申请")
            },
            error() {

            }
        });
    });
    elemet.parentNode.style.display = "none";
}

function agreeGroup(elemet) {
    let messageId = elemet.dataset.messageid;
    let groupId = elemet.dataset.groupid;
    let userId = elemet.dataset.userid;

    new Promise(() => {
        $.ajax({
            url: `/chat/addGroupMember?messageId=${messageId}&groupId=${groupId}&memberId=${userId}`,
            success() {
                alert("已同意该入群申请");
            },
            error() {

            }
        });
    });
    elemet.parentNode.style.display = "none";
}

function refuseGroup(elemet) {
    let messageId = elemet.dataset.messageid;

    new Promise(() => {
        $.ajax({
            url: `/chat/deleteMessageById?messageId=${messageId}`,
            success() {
                alert("已拒绝该入群申请")
            },
            error() {

            }
        });
    });
    elemet.parentNode.style.display = "none";
}

function logout() {
    window.location.href = "/chat/logout";
}

function replacePetname(elemet) {
    const newPetnameNode = document.createElement('input');
    newPetnameNode.style.width = "140px"
    newPetnameNode.style.height = "25px";
    newPetnameNode.style.fontSize = "16px";
    newPetnameNode.id = "petNameInput";
    newPetnameNode.value = elemet.innerText;
    newPetnameNode.onblur = cancelReplacePetname
    newPetnameNode.addEventListener("keydown", function (event) {
        if (event.key === "Enter") {
            if (newPetnameNode.value.trim() === "") {
                cancelReplacePetname();
                return
            }
            executeReplacePetname(newPetnameNode);
        }
    })
    elemet.parentNode.replaceChild(newPetnameNode, elemet);
    newPetnameNode.focus()
}

function cancelReplacePetname() {
    let petNameInput = document.querySelector("#petNameInput");
    let petNameText = document.querySelector("#petName").value;
    let petName = document.createElement("span");
    petName.innerText = petNameText;
    petName.style.display = "inline-block";
    petName.style.width = "130px";
    petName.style.cursor = "pointer";
    petName.style.whiteSpace = "nowrap";
    petName.style.overflow = "hidden";
    petName.style.textOverflow = "ellipsis"
    petName.style.verticalAlign = "middle"
    petName.onclick = function () {
        replacePetname(petName)
    }
    petNameInput.parentNode.replaceChild(petName, petNameInput);
}

function executeReplacePetname(elemet) {
    let petname = elemet.value;
    new Promise(() => {
        $.ajax({
            url: `/chat/modifyPetname?petname=${petname}`,
            success() {
                document.querySelector("#petName").value = petname;
                cancelReplacePetname()
            },
            error() {

            },
        });
    });
}

const menu = {
    "nomal": false,
    "group": false,
}

function menuOption() {
    let messageType = document.querySelector("#messageType").value;
    if (messageType === "nomal") {
        let nomalMenu = document.querySelector("#nomalMenu");
        if (!menu.nomal) {
            menu.nomal = true;
            nomalMenu.style.height = "80px";
            nomalMenu.style.padding = "10px"
            return;
        }
        menu.nomal = false;
        nomalMenu.style.height = "0";
        nomalMenu.style.padding = "0";
    }

    let role = document.querySelector("#role").value;
    const modifyGroupName = document.querySelector("#modifyGroupName");
    if (messageType === "group") {
        let groupMenu = document.querySelector("#groupMenu");
        if (!menu.group) {
            menu.group = true;
            if (parseInt(role) === 0) {
                groupMenu.style.height = "110px";
                groupMenu.style.padding = "10px"
                modifyGroupName.style.display = "list-item";
            } else {
                groupMenu.style.height = "80px";
                groupMenu.style.padding = "10px"
                modifyGroupName.style.display = "none";
            }
            return;
        }
        menu.group = false;
        groupMenu.style.height = "0";
        groupMenu.style.padding = "0";
    }
}

function deleteFriend() {

    //缩回菜单
    let nomalMenu = document.querySelector("#nomalMenu");
    menu.nomal = false;
    nomalMenu.style.height = "0";
    nomalMenu.style.padding = "0";

    let isDelete = confirm("确定要删除该好友吗?\n此操作将会删除所有的聊天记录");
    let friendId = document.querySelector("#friendId").value;
    if (isDelete) {
        new Promise(() => {
            $.ajax({
                url: `/chat/deleteFriend?friendId=${friendId}`,
                success() {
                    alert("删除成功")
                },
                error() {

                },
            });
        });
    }
}

//导出聊天记录
function exportMessage() {
    //缩回菜单
    let nomalMenu = document.querySelector("#nomalMenu");
    menu.nomal = false;
    nomalMenu.style.height = "0";
    nomalMenu.style.padding = "0";

    let friendId = document.querySelector("#friendId").value;
    window.open(`/chat/exportMessage?friendId=${friendId}`, "_blank")
}

function getGroupMember() {

    //缩回菜单
    let groupMenu = document.querySelector("#groupMenu");
    menu.group = false;
    groupMenu.style.height = "0";
    groupMenu.style.padding = "0";

    let groupId = document.querySelector("#friendId").value;
    new Promise(() => {
        $.ajax({
            url: `/chat/getMemberList?groupId=${groupId}`,
            success(memberList) {
                showGroupMember(memberList, groupId);
            },
            error() {

            },
        });
    });
}

function showGroupMember(memberList, groupId) {
    document.querySelector("#tip").click()
    document.querySelector("#exampleModalLabel").innerText = "群成员列表"
    let modalBody = document.querySelector(".modal-body");
    modalBody.innerHTML = "";

    const ul = document.createElement("ul");
    ul.classList.add("list-group");

    for (let i = 0; i < memberList.groupMember.length; i++) {
        const headImage = memberList.groupMember[i].headImage;
        const petName = memberList.groupMember[i].petName;
        const userid = memberList.groupMember[i].userid;
        const username = memberList.groupMember[i].username;
        const role = memberList.role;
        const myId = document.querySelector("#userId").value;
        if (userid.toString() !== myId && role === 0) {
            const li = document.createElement("li");
            li.classList.add("list-group-item", "group-member-item");
            li.innerHTML = `<img style="width: 50px; height: 50px; vertical-align: bottom;" src='${headImage}' alt="头像"><div style="display: inline-block"><span style="display: inline-block; width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">昵称：${petName}</span><br><span style="display: inline-block; font-size: 12px; color: #DDDDDD">用户名：${username}</span></div><button type="button" style="margin-top: -35px;" class="btn btn-danger refuse" data-memberid="${userid}" onclick="removeMemberToGroup(${userid}, ${groupId}, ${i})">移出本群</button>`
            ul.appendChild(li);
            continue;
        }
        if (userid.toString() !== myId) {
            const li = document.createElement("li");
            li.classList.add("list-group-item", "group-member-item");
            li.innerHTML = `<img style="width: 50px; height: 50px; vertical-align: bottom;" src='${headImage}' alt="头像"><div style="display: inline-block"><span style="display: inline-block; width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">昵称：${petName}</span><br><span style="display: inline-block; font-size: 12px; color: #DDDDDD">用户名：${username}</span></div>`
            ul.appendChild(li);
        }
    }
    modalBody.appendChild(ul);
}

function removeMemberToGroup(memberId, groupId, index) {
    let remove = confirm("确定将该用户移出本群吗?");
    if (remove) {
        new Promise(() => {
            $.ajax({
                url: `/chat/removeMemberToGroup?memberId=${memberId}&groupId=${groupId}`,
                success() {
                    document.querySelectorAll(".group-member-item")[index - 1].style.display = "none";
                    alert("已将该用户移出本群");
                },
                error() {

                },
            });
        });
    }
}

// 点击空白处隐藏菜单
function hideMenu() {
    const nomalMenu = document.querySelector("#nomalMenu");
    const groupMenu = document.querySelector("#groupMenu");
    const chatBarHeadMore = document.querySelector("#chat-bar-head-more");

    document.addEventListener('click', function (event) {
        let target = event.target;
        if (!nomalMenu.contains(target) && target !== chatBarHeadMore) {
            menu.nomal = false;
            nomalMenu.style.height = "0";
            nomalMenu.style.padding = "0";
        }
        if (!groupMenu.contains(target) && target !== chatBarHeadMore) {
            menu.group = false;
            groupMenu.style.height = "0";
            groupMenu.style.padding = "0";
        }
    });
}

function deleteGroup() {
    let groupId = document.querySelector("#friendId").value;
    let isSure = confirm("你确定要解散该群聊吗,这将会删除所有聊天记录");
    if (isSure) {
        new Promise(() => {
            $.ajax({
                url: `/chat/deleteGroup?groupId=${groupId}`,
                success() {
                    document.querySelector("#group").click();
                    alert("已解散该群聊")
                },
                error() {

                },
            });
        });
    }

}

function quitGroup() {
    let groupId = document.querySelector("#friendId").value;
    let isSure = confirm("你确定要退出该群聊吗?");
    if (isSure) {
        new Promise(() => {
            $.ajax({
                url: `/chat/quitGroup?groupId=${groupId}`,
                success() {
                    document.querySelector("#group").click();
                    alert("已退出该群聊")
                },
                error() {

                },
            });
        });
    }

}

function modifyGroupName() {
    const inputGroupName = document.querySelector("#inputGroupName");
    let groupName = document.querySelector("#groupName");
    let chatName = document.querySelector("#chat-name");
    inputGroupName.style.display = "block";
    groupName.placeholder = "请输入新的群组名称";
    groupName.value = chatName.innerText;

    inputGroupName.addEventListener("keydown", executeModifyGroupName)
}

function executeModifyGroupName(event) {
    if (event.key === "Enter") {
        let groupId = document.querySelector("#friendId").value;
        let groupName = document.querySelector("#groupName").value;
        new Promise(() => {
            $.ajax({
                url: `/chat/modifyGroupName?groupId=${groupId}&groupName=${groupName}`,
                success() {
                    document.querySelector("#group").click();
                    document.querySelector("#inputGroupName").style.display = "none";
                    document.querySelector("#groupName").value = "";
                    alert("群组名称修改完成")
                },
                error() {

                },
            });
        });
        document.querySelector("#inputGroupName").removeEventListener("keydown", executeModifyGroupName)
    }
}

function createGroup() {
    //让更多栏缩回去
    markMore = true;
    navbarMorebar.style.height = "0";
    navbarMorebar.style.padding = "0";

    const inputGroupName = document.querySelector("#inputGroupName");
    let groupName = document.querySelector("#groupName");
    inputGroupName.style.display = "block";
    groupName.placeholder = "请输入要创建的群组名称";

    inputGroupName.addEventListener("keydown", executeCreateGroup)
}

function executeCreateGroup(event) {
    if (event.key === "Enter") {
        let groupName = document.querySelector("#groupName").value;
        new Promise(() => {
            $.ajax({
                url: `/chat/createGroup?groupName=${groupName}`,
                success() {
                    document.querySelector("#group").click();
                    document.querySelector("#inputGroupName").style.display = "none";
                    document.querySelector("#groupName").value = "";
                    alert("群组创建完成")
                },
                error() {

                }
            });
        });
        document.querySelector("#inputGroupName").removeEventListener("keydown", executeCreateGroup)
    }
}

function chatViewScorll(event) {
    const chatView = document.querySelector("#chat-view");
    let userId = document.querySelector("#userId").value;
    let friendId = document.querySelector("#friendId").value;
    const messageType = document.querySelector("#messageType");
    const messageSize = document.querySelector("#messageSize");
    const page = document.querySelector("#page");

    if (chatView.scrollTop === 0 && messageType.value === "nomal" && parseInt(messageSize.value) === 30) {
        page.value = parseInt(page.value) + 1;
        console.log(page.value)
        new Promise(() => {
            $.ajax({
                url: `/chat/getMessageHistory?userId=${userId}&friendId=${friendId}&page=${page.value}`,
                success(messageData) {
                    messageSize.value = messageData.length
                    loadNomalMessage(messageData, chatView)
                },
                error() {

                }
            })
        })
    }

    if (chatView.scrollTop === 0 && messageType.value === "group" && parseInt(messageSize.value) === 30) {
        page.value = parseInt(page.value) + 1;
        console.log(page.value)

        new Promise(() => {
            $.ajax({
                url: `/chat/groupMessageHistory?groupId=${friendId}&page=${page.value}`,
                success(groupData) {
                    messageSize.value = groupData.messageData.length;
                    loadGroupMessage(groupData, chatView);
                },
                error() {

                }
            })
        })
    }
}

function loadNomalMessage(messageData, chatView) {
    let userHead = document.querySelector("#userHead").src;
    let userId = document.querySelector("#userId").value;

    let addHtml = '';

    for (let i = messageData.length - 1; i >= 0; i--) {
        let messageHtml = '';
        if (messageData[i].from === parseInt(userId)) {
            messageHtml = `<div class='col-md-12 chat-message my'><div class='card'><div class='card-body'>${messageData[i].message}</div></div><img src='${userHead}' class='middle-user-head' alt='头像'></div>`;
        } else {
            let friendHead = document.getElementById(messageData[i].from + "-head").src;
            messageHtml = `<div class='col-md-12 chat-message'><img src='${friendHead}' class='middle-user-head' alt='头像'><div class='card'><div class='card-body'>${messageData[i].message}</div></div></div>`;
        }

        let timeSplit = messageData[i].dateFormat.split("-");
        let timeHtml = `<div class="message-time">${timeSplit[0]} ${timeSplit[1]}</div>`;

        addHtml = timeHtml + messageHtml + addHtml;
    }

    // 存储当前滚动位置
    let currentScrollHeight = chatView.scrollHeight;

    chatView.innerHTML = addHtml + chatView.innerHTML;

    // 计算新消息的高度
    let newHeight = chatView.scrollHeight - currentScrollHeight;

    // 恢复之前的滚动位置
    chatView.scrollTop += newHeight;
}

function loadGroupMessage(groupData, chatView) {
    let addHtml = '';
    let userId = document.querySelector("#userId").value;

    let userHead = document.querySelector("#userHead").src;

    for (let i = groupData.messageData.length - 1; i >= 0; i--) {
        let messageHtml = '';

        let senderHead = groupData.messageData[i].senderHead;
        let senderPetName = groupData.messageData[i].senderPetName;

        if (groupData.messageData[i].senderId === parseInt(userId)) {
            messageHtml = `<div class='col-md-12 chat-message my'><div class='card'><div class='card-body'>${groupData.messageData[i].content}</div></div><img src='${userHead}' class='middle-user-head' alt='头像'></div>`;
        } else {
            messageHtml = `<div class='col-md-12 chat-message'><div id="senderPetName">${senderPetName}</div><img src='${senderHead}' class='middle-user-head' alt='头像'><div class='card sender'><div class='card-body'>${groupData.messageData[i].content}</div></div></div>`;
        }

        let timeSplit = groupData.messageData[i].dateFormat.split("-");
        let timeHtml = `<div class="message-time">${timeSplit[0] + " " + timeSplit[1]}</div>`;

        addHtml = timeHtml + messageHtml + addHtml;
    }

    // 存储当前滚动位置
    let currentScrollHeight = chatView.scrollHeight;

    chatView.innerHTML = addHtml + chatView.innerHTML;

    // 计算新消息的高度
    let newHeight = chatView.scrollHeight - currentScrollHeight;

    // 恢复之前的滚动位置
    chatView.scrollTop += newHeight;
}

function clearLocalStorage() {
    localStorage.clear();
    document.querySelector("#openAI").click();
    alert("缓存清理完成")
}